package com.wormhole.wormholemanagement.controller;

import cn.hutool.core.date.DateUtil;
import com.wormhole.wormholemanagement.controller.request.LoginRequest;
import com.wormhole.wormholemanagement.controller.response.AuthResponse;
import com.wormhole.wormholemanagement.controller.response.UserInfo;
import com.wormhole.wormholemanagement.entity.Operator;
import com.wormhole.wormholemanagement.repository.OperatorRepository;
import com.wormhole.wormholemanagement.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class LoginController {
    private final OperatorRepository operatorRepository;
    private final PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil; // 统一使用这个工具类

    public LoginController(OperatorRepository operatorRepository,
                           PasswordEncoder passwordEncoder,
                           @Value("${jwt.secret-key}") String base64SecretKey) {
        this.operatorRepository = operatorRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @PostMapping("/login")
    public ResponseEntity<AuthResponse> apiLogin(
            @RequestBody LoginRequest request) {

        // 1. 验证用户名密码
        Operator operator = operatorRepository.findByUsername(request.username())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!passwordEncoder.matches(request.password(), operator.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        // 更新最后登录时间
        operator.setLastLogin(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        operatorRepository.save(operator);

        // 2. 使用JwtUtil生成token
        String token = jwtUtil.generateToken(operator);

        // 3. 构建返回数据
        UserInfo userInfo = new UserInfo(
                operator.getOperatorId(),
                operator.getUsername(),
                operator.getRealName(),
                operator.getRole(),
                operator.getDepartment()
        );

        return ResponseEntity.ok(new AuthResponse(
                token,
                userInfo,
                3600000 // token有效期(秒)
        ));
    }
}

